package com.zheng.controller;

import com.zheng.common.Result;
import com.zheng.config.MailConfig;
import com.zheng.entity.MailDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.util.*;

@RestController
@RequestMapping("/email")
public class QqEmailController {

    @Autowired
    private JavaMailSender javaMailSender;

    //发件人邮箱
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private MailConfig mailConfig;
    /**
     * 不带附件发送邮件
     * addressee 收件人邮箱
     * subject 邮件标题
     * content 邮件内容
     * @return ResultVO
     */
    @PostMapping("/send")
    public Result sendEmail(@RequestBody MailDto mail) throws AddressException {
        //判断文件格式是否正确
        //获取收件人邮箱
        String addressee = mail.getAddressee();
        if(!addressee.contains("@qq.com")){
            return Result.error("502","邮箱格式错误");
        }
        //生成随机6位数字
        StringBuilder sb = (StringBuilder)imgCode().getData();

        mail.setSubject(mailConfig.getSubject());
        mail.setContent(mailConfig.getContentPrefix()+sb+mailConfig.getContentSuffix());

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        // 发件人邮箱,与配置文件中保持一致,所以直接从配置文件绑定过来了
//        mailMessage.setFrom(String.valueOf(new InternetAddress("大浪8" + "<" + from + ">")));
        mailMessage.setFrom(from);
        // 收件人
        mailMessage.setTo(mail.getAddressee());
        // 标题
        mailMessage.setSubject(mail.getSubject());
        // 内容, 第一个参数为邮箱内容, 第二个参数为是否启用html格式,
        // 如果开启, 那么第一个参数如果有html标签, 会自动识别, 邮件样式更好看
        mailMessage.setText(mail.getContent());
        try {
            javaMailSender.send(mailMessage);
            return Result.success(sb.toString()); // 返回验证码
        } catch (MailAuthenticationException e) {
            return Result.error("530", "认证失败，请检查授权码和SSL配置");
        } catch (MailSendException e) {
            return Result.error("531", "邮件发送失败，请检查网络和配置");
        }
        //返回验证码
//        return Result.success();
    }

    @GetMapping("/getImgCode")
    public Result imgCode(){
        //生成随机6位数字
        SecureRandom secureRandom = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(secureRandom.nextInt(10));
        }
        return Result.success(sb);
    }

    /**
     * 新增：接收最新的N封邮件
     * @param count 要获取的邮件数量（默认10封）
     * @return 邮件列表（包含发件人、主题、内容）
     */
    @GetMapping("/receive")
    public Result receiveEmails(@RequestParam(defaultValue = "10") int count) {
        try {
            // 1. 配置IMAP服务器（QQ邮箱使用IMAP协议）
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "imap");
            props.setProperty("mail.imap.host", "imap.qq.com");
            props.setProperty("mail.imap.port", "993");
            props.setProperty("mail.imap.ssl.enable", "true");

            // 2. 创建Session并连接邮件服务器
            Session session = Session.getInstance(props);
            Store store = session.getStore("imap");
            store.connect("imap.qq.com", from, "atqxbylewurmdcei"); // 使用授权码登录

            // 3. 打开收件箱
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY); // 只读模式

            // 4. 获取最新的N封邮件
            Message[] messages = inbox.getMessages();
            int totalMessages = Math.min(count, messages.length);

            List<Map<String, String>> emailList = new ArrayList<>();
            for (int i = messages.length - 1; i >= messages.length - totalMessages; i--) {
                Message message = messages[i];
                Map<String, String> emailInfo = new HashMap<>();

                emailInfo.put("from", InternetAddress.toString(message.getFrom()));
                emailInfo.put("subject", message.getSubject());
                emailInfo.put("content", message.getContent().toString());
                emailInfo.put("date", message.getSentDate().toString());

                emailList.add(emailInfo);
            }

            // 5. 关闭连接
            inbox.close(false);
            store.close();

            return Result.success(emailList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "接收邮件失败: " + e.getMessage());
        }
    }


    /**
     * 新增：获取最新邮件中的 PDF 附件
     * @param count 检查的最新邮件数量（默认5封）
     * @return 包含 PDF 附件的 Base64 编码和文件名
     */
    @GetMapping("/pdfAttachments")
    public Result getPdfAttachments(@RequestParam(defaultValue = "5") int count) {
        try {
            // 1. 配置IMAP服务器
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "imap");
            props.setProperty("mail.imap.host", "imap.qq.com");
            props.setProperty("mail.imap.port", "993");
            props.setProperty("mail.imap.ssl.enable", "true");

            // 2. 连接邮箱服务器
            Session session = Session.getInstance(props);
            Store store = session.getStore("imap");
            store.connect("imap.qq.com", from, "atqxbylewurmdcei");

            // 3. 打开收件箱
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);

            // 4. 获取最新的N封邮件
            Message[] messages = inbox.getMessages();
            int totalMessages = Math.min(count, messages.length);

            List<Map<String, String>> pdfAttachments = new ArrayList<>();

            // 5. 遍历邮件，查找PDF附件
            for (int i = messages.length - 1; i >= messages.length - totalMessages; i--) {
                Message message = messages[i];
                if (message.isMimeType("multipart/*")) {
                    Multipart multipart = (Multipart) message.getContent();
                    for (int j = 0; j < multipart.getCount(); j++) {
                        BodyPart bodyPart = multipart.getBodyPart(j);
                        if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                            String fileName = bodyPart.getFileName();
                            if (fileName != null && fileName.toLowerCase().endsWith(".pdf")) {
                                // 读取PDF附件
                                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                bodyPart.getDataHandler().writeTo(outputStream);
                                byte[] pdfBytes = outputStream.toByteArray();

                                // 转换为Base64
                                String base64Pdf = Base64.getEncoder().encodeToString(pdfBytes);

                                Map<String, String> attachmentInfo = new HashMap<>();
                                attachmentInfo.put("fileName", fileName);
                                attachmentInfo.put("base64Content", base64Pdf);
                                pdfAttachments.add(attachmentInfo);
                            }
                        }
                    }
                }
            }

            // 6. 关闭连接
            inbox.close(false);
            store.close();

            return Result.success(pdfAttachments);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("500", "获取PDF附件失败: " + e.getMessage());
        }
    }



}
